import { Strategy, IStrategyOptions } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, BadRequestException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { compareSync } from 'bcryptjs';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      usernameField: 'username',
      passwordField: 'password'
    } as IStrategyOptions);
  }

  async validate(username: string, pass: string): Promise<any> {
    const user = await this.authService.validateUser(username, pass);
    if (!user) {
      throw new BadRequestException('用户名不正确！');
    }
    if (!compareSync(pass, user.password)) {
      throw new BadRequestException('密码错误!');
    }
    if (!user.status) {
      throw new BadRequestException('用户被禁用！');
    }
    const { password, roles, ...result } = user; // 剔除密码再返回
    // 初始化 role 数组
    const roleNames = roles.map((role) => ({ name: role.name, id: role.id }));
    const userData = { ...result, role: roleNames }
    return userData;
  }
}